package com.fuyun.rpc.transmission.socket.server;

import com.fuyun.rpc.dto.RpcReq;
import com.fuyun.rpc.dto.RpcResp;
import com.fuyun.rpc.handler.RpcReqHandler;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @Author fuyun。
 * @Date 2025/8/21 17:53。
 * @Description: TODO。
 **/
@Slf4j
@AllArgsConstructor
public class SocketReqHandler implements Runnable {

    private final Socket socket;
    private final RpcReqHandler rpcReqHandler;

    @Override
    @SneakyThrows
    public void run() {
        ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
        RpcReq rpcReq = (RpcReq) objectInputStream.readObject();
        System.out.println(rpcReq);

        ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
        RpcResp<?> success = RpcResp.success(rpcReq.getRequestId(), rpcReqHandler.invoke(rpcReq));
        objectOutputStream.writeObject(success);
        objectOutputStream.flush();
    }
}
